package com.lvyq.service.impl;

import com.lvyq.common.GoodsTypeConstant;
import com.lvyq.model.bag.MyBag;
import com.lvyq.model.farm.*;
import com.lvyq.model.goods.GoodsRelation;
import com.lvyq.model.receive.ReceiveMsg;
import com.lvyq.model.shop.ShopGoods;
import com.lvyq.model.user.User;
import com.lvyq.repository.*;
import com.lvyq.service.MyFarmService;
import com.lvyq.util.DateUtil;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: 小窝农场
 * @description:
 * @author: lvyq
 * @create: 2023-04-04 20:35
 **/
@Service
public class MyFarmServiceImpl implements MyFarmService {

    @Resource
    private MyFarmRepository myFarmRepository;

    @Resource
    private MyLandRepository myLandRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private GoodsRelationRepository goodsRelationRepository;

    @Resource
    private MyPlantRepository myPlantRepository;


    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MyBagRepository myBagRepository;

    @Resource
    private FertilizerRepository fertilizerRepository;

    @Resource
    private ShopGoodsRepository shopGoodsRepository;

    @Resource
    private FarmGradeRepository farmGradeRepository;

    @Override
    public String orderReply(String replyContent, ReceiveMsg receiveMsg) {

        //购买土地
        if (receiveMsg.getContent().equals("购买土地")){
            replyContent=myLandReply(replyContent,receiveMsg);
        }

        //小窝农场
        if (receiveMsg.getContent().equals("小窝农场")){
            replyContent=myFarmReply(replyContent,receiveMsg);
        }
        //种植
        if (receiveMsg.getContent().startsWith("种植#")){
            replyContent=myPlantReply(replyContent,receiveMsg);
        }

        //采集
        if (receiveMsg.getContent().equals("采集")){
            replyContent=getGoodsReply(replyContent,receiveMsg);
        }
        //施肥  施肥#初级肥料*3
        if (receiveMsg.getContent().startsWith("施肥#")){
            replyContent=sFReply(replyContent,receiveMsg);
        }

        return replyContent;
    }

    /**
    * @Description:施肥
     * @param replyContent
   * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/16 20:43
    */
    private String sFReply(String replyContent, ReceiveMsg receiveMsg) {
        //获取肥料种类及数量
        Integer useNum=0;
        String content = receiveMsg.getContent();
        String goodsName = content.split("#")[1].split("\\*")[0];
        String goodsNum = content.split("#")[1].split("\\*")[1];
        //判断物品是否可用于施肥
        Fertilizer fertilizer = fertilizerRepository.findByGoodName(goodsName);
        if (fertilizer==null){
            replyContent="施肥失败,"+goodsName+"不是肥料，请正确使用物品";
            return replyContent;
        }
        //判断数量是否充足
        MyBag myBag = myBagRepository.findByGoodsNameAndOpenId(goodsName,receiveMsg.getFromUserName());
        if (myBag==null){
            replyContent="施肥失败,"+goodsName+"不存在,请先购买物品";
            return replyContent;
        }
        if(myBag.getNum()<Integer.valueOf(goodsNum)){
            replyContent="施肥失败,"+goodsName+"不足";
            return replyContent;
        }
        //判断是否需要消耗肥料
        List<MyPlant> myPlants = myPlantRepository.findAllByOpenId(receiveMsg.getFromUserName());
        if (myPlants.size()>0){
            for (MyPlant myPlant:myPlants){
                if (Integer.valueOf(goodsNum)==useNum){
                    break;
                }
                useNum=useNum+1;
                if (myPlant.getState()==0){
                    myPlant.setEndTime(myPlant.getEndTime()-(fertilizer.getReduceTime()*60*1000));
                    if (myPlant.getEndTime()<new Date().getTime()){
                        myPlant.setState(1);
                    }
                    mongoTemplate.save(myPlant);
                }else {
                    continue;
                }
            }
            //修改背包数量
            myBag.setNum(myBag.getNum()-useNum);
            if (myBag.getNum()==0){
                //删除数据
                Query query=  new Query().addCriteria(Criteria.where("goodsName").is(goodsName)).addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()));
                mongoTemplate.remove(query,MyBag.class);
            }else {
                myBagRepository.save(myBag);
            }
            //处理返回消息
            replyContent=replyContent.replace("{num}",useNum.toString()).replace("{goodsName}",goodsName);
            return replyContent;
        }else {
            replyContent="施肥失败,当前农场未种植作物";
            return replyContent;
        }
    }


    /** 
    * @Description: 采集
    * @params:  * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/8 19:28
    */
    private String getGoodsReply(String replyContent, ReceiveMsg receiveMsg) {
        //查询种植表，判断作物状态
        List<MyPlant> myPlants = myPlantRepository.findAllByOpenId(receiveMsg.getFromUserName());
        //标识是否存在成熟作物。
        boolean iscs=true;
        StringBuffer stringBuffer = new StringBuffer();
        Integer jingyan=0;
        if (myPlants.size()>0){
            //采集操作，就是删除对应的种植记录。
            for (MyPlant myPlant:myPlants){
                if (myPlant.getState()==1){
                    iscs=false;
                    GoodsRelation goodsRelation = goodsRelationRepository.findByStartGoodsName(myPlant.getGoodsName());
                    //存储到背包中
                    MyBag myBag = myBagRepository.findByGoodsNameAndOpenId(goodsRelation.getEndGoodsName(),receiveMsg.getFromUserName());
                    if (myBag!=null){
                        myBag.setNum(myBag.getNum()+goodsRelation.getReapNum());
                        mongoTemplate.save(myBag);
                    }else {
                        myBag=new MyBag();
                        myBag.setNum(goodsRelation.getReapNum());
                        myBag.setOpenId(receiveMsg.getFromUserName());
                        myBag.setGoodsName(goodsRelation.getEndGoodsName());
                        mongoTemplate.save(myBag);
                    }
                    Query query = new Query().addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()))
                            .addCriteria(Criteria.where("landNo").is(myPlant.getLandNo()));
                    mongoTemplate.remove(query,MyPlant.class);
                    stringBuffer.append(goodsRelation.getEndGoodsEmoji()+goodsRelation.getEndGoodsName()+"*"+goodsRelation.getReapNum()+"，" +
                            goodsRelation.getJingyan()+"经验\n");
                    jingyan=jingyan+goodsRelation.getJingyan();

                }else {
                    continue;
                }
            }
            if (iscs){
                replyContent="采集失败，您种植的作物还未成熟";
                return replyContent;
            }else {
                replyContent=replyContent.replace("{goods}",stringBuffer.toString());
                //TODO 修改农场经验
                MyFarm myFarm = myFarmRepository.findByOpenId(receiveMsg.getFromUserName());
                myFarm.setJingYan(myFarm.getJingYan()+jingyan);
                List<FarmGrade> farmGrades = mongoTemplate.findAll(FarmGrade.class);
                List<Integer> jys= new ArrayList<>();
                for (FarmGrade farmGrade:farmGrades){
                    jys.add(farmGrade.getJingYanVal());
                }
                //判断经验等级
                Integer lv = checkJY(myFarm.getJingYan(),jys);
                myFarm.setLevel(lv+1);
                myFarm.setMaxLand(myFarm.getLevel()*3);
                mongoTemplate.save(myFarm);
            }
        }else {
            replyContent="采集失败，您还没有种植作物";
        }

        return replyContent;
    }

    /** 
    * @Description: 判断经验等级
    * @params:  * @param jingYan
 * @param jys
    * @return: {@link java.lang.Integer}
    * @Author: lvyq
    * @Date: 2023/4/9 16:04
    */
    private Integer checkJY(Integer uJingyan, List<Integer> jys) {
        int left=0;
        int right=jys.size()-1;
        int resut=0;
        while (left<=right){
            int mid = (left+right)/2;
            if (uJingyan<jys.get(mid)){
                right=mid;
                if (right==resut){
                    break;
                }
                resut=right;
            }
            if (uJingyan>jys.get(mid)){
                left=mid;
                if (left==resut){
                    break;
                }
                resut=left;
            }
            if(uJingyan==jys.get(mid)){
                resut=mid;
                break;
            }

        }
        return resut;
    }

    /**
    * @Description: 种植
    * @params:  * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/8 9:09
    */
    private String myPlantReply(String replyContent, ReceiveMsg receiveMsg) {
        MyFarm myFarm = myFarmRepository.findByOpenId(receiveMsg.getFromUserName());
        if (myFarm==null){
            replyContent="种植失败，您当前未拥有土地，请【购买土地】";
            return replyContent;
        }
        Integer useNum=0;
        String content = receiveMsg.getContent();
        //麦子种子*1
        String goodsName = content.split("#")[1].split("\\*")[0];
        String goodsNum = content.split("#")[1].split("\\*")[1];
        ShopGoods goods =shopGoodsRepository.findByGoodsName(goodsName);
        //查询背包
        MyBag myBag = myBagRepository.findByGoodsNameAndOpenId(goodsName,receiveMsg.getFromUserName());
        if (myBag==null){
            replyContent="种植失败,背包中不存在此物品";
            return replyContent;
        }
        //判断数量
        if (myBag.getNum()<Integer.valueOf(goodsNum)){
            replyContent="种植失败,物品不足";
            return replyContent;
        }
        //判断是否可被种植
        if (goods!=null){
            if (goods.getGoodsType()!=GoodsTypeConstant.NC_ZZ){
                replyContent="种植失败，当前物品无法种植";
                return replyContent;
            }
            GoodsRelation goodsRelation = goodsRelationRepository.findByStartGoodsName(goodsName);
            if (goodsRelation!=null){
                //判断作物等级与农场等级是否匹配
                if (goodsRelation.getGoodsLevel()>myFarm.getLevel()){
                    replyContent="种植失败，当前作物为"+goodsRelation.getGoodsLevel()+"级作物,农场等级不足,请升级农场";
                    return replyContent;
                }
                //判断已经拥有的土地是否被种植
              List<MyPlant> myPlants = myPlantRepository.findAllByOpenId(receiveMsg.getFromUserName());
              List<MyLand> myLands = myLandRepository.findByOpenId(receiveMsg.getFromUserName());
              //现在的土地种植数
              Integer myPlansNum=myPlants.size();
              //拥有的土地数
              Integer myLandNum=myLands.size();
              //空余土地数
              Integer kyNum=myLandNum-myPlansNum;
              if (kyNum==0){
                  replyContent="种植失败，已无空地可被种植，请【购买土地】";
                  return replyContent;
              }else {
                  for (MyLand myLand:myLands){
                      MyPlant myPlant= myPlantRepository.findByOpenIdAndLandNo(receiveMsg.getFromUserName(),myLand.getLandNo());
                      if (myPlant==null){
                          if (useNum>=Integer.valueOf(goodsNum)){
                              break;
                          }
                          useNum=useNum+1;
                          long startTime=new Date().getTime();
                          long endTime=startTime+(goodsRelation.getMaturityTime()*1000*60);
                          myPlant=new MyPlant();
                          myPlant.setOpenId(myLand.getOpenId());
                          myPlant.setGoodsName(goodsName);
                          myPlant.setLandNo(myLand.getLandNo());
                          myPlant.setStartTime(startTime);
                          myPlant.setEndTime(endTime);
                          myPlant.setState(0);
                          myPlantRepository.save(myPlant);
                      }
                  }
                  //修改背包数量
                  myBag.setNum(myBag.getNum()-useNum);
                  if (myBag.getNum()==0){
                      //删除数据
                      Query query=  new Query().addCriteria(Criteria.where("goodsName").is(goodsName)).addCriteria(Criteria.where("openId").is(receiveMsg.getFromUserName()));
                      mongoTemplate.remove(query,MyBag.class);

                  }else {
                      myBagRepository.save(myBag);
                  }

                  //处理返回消息
                  replyContent=replyContent.replace("{num}",useNum.toString()).replace("{goodsName}",goodsName);
                  return replyContent;
              }
            }else {
                replyContent="种植失败，物品不存在";
                return replyContent;
            }
        }else {
            replyContent="种植失败，物品不存在";
        }
        return replyContent;
    }


    /** 
    * @Description: 小窝农场
    * @params:  * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/4 20:58
    */
    private String myFarmReply(String replyContent, ReceiveMsg receiveMsg) {
        MyFarm myFarm = myFarmRepository.findByOpenId(receiveMsg.getFromUserName());
        List<MyLand> myLands = myLandRepository.findByOpenId(receiveMsg.getFromUserName());
        String myLand="";
        StringBuffer stringBuffer =new StringBuffer();
        for (MyLand land:myLands){
            MyPlant myPlant = myPlantRepository.findByOpenIdAndLandNo(receiveMsg.getFromUserName(),land.getLandNo());
            if (myPlant!=null){
                GoodsRelation goodsRelation = goodsRelationRepository.findByStartGoodsName(myPlant.getGoodsName());
                if (myPlant.getState()==1 || new Date().getTime()>myPlant.getEndTime()){
                    stringBuffer.append(land.getLandNo()+"号土地-"+goodsRelation.getEndGoodsEmoji()+goodsRelation.getEndGoodsName()+"(已成熟)\n");
                }else {
                    //成长中
                    stringBuffer.append(land.getLandNo()+"号土地-"+goodsRelation.getEndGoodsEmoji()+goodsRelation.getEndGoodsName()+"\n");
                    stringBuffer.append("   "+DateUtil.timeChange(myPlant.getEndTime())+"后作物成熟\n");
                }

            }else {
                stringBuffer.append("#"+land.getLandNo()+"号土地\n");
            }

        }
        myLand=stringBuffer.toString();
        if (myFarm!=null){
            FarmGrade farmGrade =farmGradeRepository.findByDengJi(myFarm.getLevel()+1);
            replyContent=replyContent.replace("{lv}",myFarm.getLevel().toString())
                    .replace("{crop}",myLands.size()+"/"+myFarm.getMaxLand())
                    .replace("{jingyan}",myFarm.getJingYan().toString()+"/"+farmGrade.getJingYanVal())
                    .replace("{land}",myLand);
        }else {
            replyContent="您当前未购买土地，请【购买土地】!";
        }
        return replyContent;
    }

    /** 
    * @Description: 购买土地
    * @params:  * @param replyContent
    * @param receiveMsg
    * @return: {@link java.lang.String}
    * @Author: lvyq
    * @Date: 2023/4/4 20:40
    */
    private String myLandReply(String replyContent, ReceiveMsg receiveMsg) {
        MyFarm myFarm = myFarmRepository.findByOpenId(receiveMsg.getFromUserName());
        List<MyLand> myLands = myLandRepository.findByOpenId(receiveMsg.getFromUserName());
        User user =userRepository.findByOpenId(receiveMsg.getFromUserName());
        //土地金额200金币
        if (user.getJinbi()>=200){
            //如果myLands为空，则表示用户第一次购买
            Integer myLandNum=myLands.size();
            if (myLands.size()>0){
                Integer maxLandNum=myFarm.getMaxLand();
                if (myLandNum>=maxLandNum){
                    replyContent="您已无法购买土地，请升级农场！";
                }else {
                    MyLand myLand = new MyLand();
                    myLand.setOpenId(receiveMsg.getFromUserName());
                    myLand.setLandNo(myLandNum+1);
                    myLandRepository.save(myLand);
                }
            }else {
                myFarm = new MyFarm();
                myFarm.setOpenId(receiveMsg.getFromUserName());
                myFarm.setMaxLand(3);
                myFarm.setLevel(1);
                myFarm.setJingYan(0);
                myFarmRepository.save(myFarm);
                MyLand myLand = new MyLand();
                myLand.setOpenId(receiveMsg.getFromUserName());
                myLand.setLandNo(1);
                myLandRepository.save(myLand);
            }
            user.setJinbi(user.getJinbi()-200);
            userRepository.save(user);
        }else {
            replyContent="金币不足，土地购买失败！";
        }

        return replyContent;

    }
}
